#!/bin/bash
if [ "$1" == "" ]; then 
#	TAG=2023.02.3
        TAG=2023.11-rc1
else
	TAG=$1
fi

cd `dirname $0`

BRDIR=buildroot-${TAG}

cd `dirname $0`
cd ..

if [ -d $BRDIR ]; then
	echo "Saving current buildroot"
	rm -rf $BRDIR.bak
	mv $BRDIR $BRDIR.bak
fi

echo "Checking out buildoot tag ${TAG} from Github"
git clone https://github.com/buildroot/buildroot $BRDIR

echo "Checking out a known-good release"
pushd $BRDIR
git checkout $TAG

if [ -f ../hifiberry-os/buildroot/buildroot-${TAG}.patch ]; then
	echo "Applying patch"
	patch -p1 < ../hifiberry-os/buildroot/buildroot-${TAG}.patch
else	
	ls ../hifiberry-os/buildroot/buildroot-${TAG}.patch
	echo "No patch found - is this correct?"
fi
popd

#echo "Copying genimage configurations"
#cp -v hifiberry-os/buildroot/board/raspberrypi/genimage*cfg $BRDIR/board/raspberrypi

echo "Fixing genimage configurations"
if [ -f $BRDIR/board/raspberrypi/genimage.cfg.in ]; then
	# Latest buildroot versions use a generic genimage file
	i=$BRDIR/board/raspberrypi/genimage.cfg.in
	mv $i $i.bak
	cat $i.bak | sed s/32M/256M/g > $i
else
	for i in $BRDIR/board/raspberrypi/genimage*cfg; do
		mv $i $i.bak
		# Resize FAT partition to 100M as we want to store backup files there
		cat $i.bak | sed s/32M/128M/g > $i
	done
fi

echo "Symlinking to buildroot"
rm buildroot
ln -s $BRDIR buildroot

